<template>
  <div class="my-account-container">
    <div class="box-card">
      <div class="title">我的账号</div>
      <div class="info-wrap">
        <div class="info-item" v-for="(item,index) in accountInfoList" :key="index">
          <div class="name">{{item.title}}<span>：</span></div>
          <div class="content">
            <span class="content-info" v-if="item.field === 'mobile'">{{item.value | hidePhoneFourRank}}</span>
            <span class="content-info" v-if="!['mobile', 'status'].includes(item.field)">{{item.value}}</span>
             <span class="content-info" v-if="item.field == 'status'">{{acountStatus[item.value]}}</span>
            <span class="content-icon bind-icon" v-if="item.field === 'mobile' && item.value === '--'" @click="showBindPhone=true">请绑定</span>
            <template v-else>
              <span class="content-icon" v-if="item.field === 'mobile' && item.value" @click="changePhone('changeBindPhone')">换绑</span>
              <span class="content-icon" v-if="item.field === 'mobile' && item.value" @click="changePhone('verPhone')">解绑</span>
            </template>
          </div>
        </div>
      </div>
      <div>
        <el-button class="search-btn" type="primary" size="medium" @click="handleAccountShow">修改信息</el-button>
        <el-button class="search-btn" type="primary" size="medium" @click="dialogFormVisible = true">修改密码</el-button>
      </div>
    </div>
    <el-dialog width="600px" title="修改密码" :visible.sync="dialogFormVisible" center @closed="resetInfo('form')">
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="旧密码：" prop="oldPassword" :label-width="formLabelWidth">
          <el-input v-model="form.oldPassword" placeholder="请输入旧密码" size="medium" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码：" prop="password" :label-width="formLabelWidth">
          <el-input v-model="form.password" placeholder="请输入新密码"  size="medium" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmPassword" :label-width="formLabelWidth">
          <el-input v-model="form.confirmPassword" placeholder="请确认密码" size="medium" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div class="passRule">
        <span class="title">密码规则：</span>
        <span class="word">1、密码必须同时含有大小写字母、数字、特殊字符中的两种</span>
        <span class="word">2、密码的长度必须是8-20位；</span>
        <span class="word">3、登录密码不能连续出现4个以及以上或相邻的，如0000，1234，abcd；</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" size="medium">取 消</el-button>
        <el-button class="search-btn" type="primary" @click="passSubmit('form')" size="medium">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog width="550px" title="账号信息编辑" :visible.sync="isShowAccount" center @closed="resetInfo('fromModify')">
      <el-form :model="fromModify" :rules="rules" ref="fromModify">
        <el-form-item label="员工姓名：" prop="userName" :label-width="formLabelWidth">
          <el-input v-model="fromModify.userName" placeholder="请输入姓名" maxlength="15" size="medium" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="员工邮箱：" :label-width="formLabelWidth">
          <el-input v-model="fromModify.email"  placeholder="请输入邮箱" size="medium" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="登录账号：" :label-width="formLabelWidth">{{userInfo.account}}</el-form-item>
        <el-form-item label="手机号码：" :label-width="formLabelWidth">{{userInfo.mobile | hidePhoneFourRank}}</el-form-item>
        <el-form-item label="账号状态：" :label-width="formLabelWidth">{{acountStatus[userInfo.status]}}</el-form-item>
        <el-form-item label="角色类型：" :label-width="formLabelWidth">{{userInfo.accountName}}</el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="search-btn" type="primary" @click="modifySubmit('fromModify')" size="medium">确 认</el-button>
        <el-button @click="isShowAccount = false" size="medium">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 绑定 -->
    <bind-phone ref="bindPhone" v-if="showBindPhone" @close="showBindPhone=false;handleValue()"></bind-phone>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import BindPhone from './components/BindPhone'
import MD5 from 'md5'
import { updatePassword, updateSelfAccount } from '@/api/account'
import store from '@/store'
export default {
  components:{
    BindPhone
  },
  data () {
    const validateCheckPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    }
    const validateCheckName = (rule, value, callback) => {
      const reg = /^[A-Za-z\u4e00-\u9fa5]+$/
      if (value === '') {
        callback(new Error('请输入姓名'));
      } else if (!reg.test(value)) {
        callback(new Error('只允许输入汉字和字母'))
      } else {
        callback();
      }
    }
    return {
      isShowAccount: false,
      dialogFormVisible: false,
      form: {
        oldPassword: '',
        password: '',
        confirmPassword: ''
      },
      fromModify: {
        userName: '',
        email: ''
      },
      acountStatus:{
        0: '离职',
        1: '在职'
      },
      formLabelWidth: '100px',
      accountInfoConfig: [
        { title: '员工姓名', field: 'userName', value: '' },
        { title: '员工邮箱', field: 'email', value: '' },
        { title: '登录账号', field: 'account',  value: '' },
        { title: '手机号', field: 'mobile', value: '--' },
        { title: '账号状态', field: 'status', value: '' },
        { title: '角色类型', field: 'accountName', value: '' }
      ],
      accountInfo: [],
      showBindPhone: false,
      rules: {
        userName: [{ required: true, validator: validateCheckName, trigger: 'change' }],
        email: [{ required: true, type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change']}],
        oldPassword: [{ required: true, message: '请输入旧密码', trigger: 'change' }],
        password: [{ required: true, validator: this.validetePassword, trigger: 'change' }],
        confirmPassword: [{ required: true, validator: validateCheckPass, trigger: 'change' }]

      }
    }
  },
  mounted () {
    this.handleValue()
  },
  computed: {
    accountInfoList () {
      return this.accountInfo.filter(item => item.value)
    },
    ...mapState('user', {
      userInfo: state => state.userInfo
    })
  },
  watch: {
    userInfo: {
      deep: true,
      handler () {
        this.handleValue()
      }
    }
  },
  methods: {
    // 展示信息
    handleAccountShow () {
      this.fromModify.userName = this.accountInfo[0].value
      this.fromModify.email = this.accountInfo[1].value
      this.isShowAccount = true
    },
    handleValue () {
      this.accountInfo = this.accountInfoConfig.map(item => {
        if (this.userInfo[item.field]) {
          return {...item, value: this.userInfo[item.field]}
        } 
        return {...item}
      })
    },
    // 关闭信息弹框
    resetInfo (formName) {
      this.$refs[formName].resetFields()
    },
    // 修改信息提交
    modifySubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        // const reg = /^\w+@[a-z0-9]+\.[a-z]{2,4}$/
        // if (this.fromModify.email && !reg.test(this.fromModify.email)) {
        //   this.$message.info('请输入正确邮箱格式')
        // }
        this.updateSelfAccountApi(this.fromModify)
      })
    },
    // 修改密码
    passSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return
        const { oldPassword, password, confirmPassword } = this.form
        const params = {}
        params.oldPassword = MD5(oldPassword)
        params.password = MD5(password)
        params.confirmPassword = MD5(confirmPassword)
        this.updatePasswordApi(params)
      })
    },
    changePhone (name) {
      this.$router.push({ name })
    },
    // 退出登录
    logout () {
      store.dispatch('permission/resetPermission')
      store.dispatch('user/clearInfo')
    },
    // 修改信息提交接口
    async updateSelfAccountApi (params) {
      try {
        const { code, result } = await updateSelfAccount(params)
        if (code !== 200) return
        this.isShowAccount = false
        const { userName, email } = result
        const copyUserInfo = { ...this.userInfo }
        copyUserInfo.userName = userName
        copyUserInfo.email = email
        this.$store.dispatch('user/setUserInfo', JSON.parse(JSON.stringify(copyUserInfo)))
      } catch (e) {
        console.log(e)
      }
    },
    // 修改密码上线
    async updatePasswordApi (params) {
      try {
        const { code } = await updatePassword(params)
        if (code !== 200) return
        this.dialogFormVisible = false
        this.logout()
      } catch (e) {
        console.log(e)
      }
    },
    // 校验密码规则
    validetePassword (rule, value, callback) {
      const reg = /^[a-zA-Z0-9！@#-_]{8,20}$/
      // 校验连续字符
      function validateContinue (str) {
        for (let i = 0; i < str.length; i++) {
          let num = str[i].charCodeAt()
          let continueStr = str[i] + String.fromCharCode(num + 1) + String.fromCharCode(num + 2) + String.fromCharCode(num + 3)
          if (continueStr === (str[i] + str[i + 1] + str[i + 2] + str[i + 3])) return continueStr
        }
        return ''
      }
      if (/(.)\1\1\1/.test(value)) {
        callback(new Error('请勿出现四个及以上重复字符'))
      } else if (!reg.test(value)) {
        callback(new Error('请输入正确格式的密码'))
      } else {
        if ((/[a-z]/.test(value) + /[A-Z]/.test(value) + /[0-9]/.test(value) + /[_！@#-]/.test(value)) < 2) {
          callback(new Error('密码必须同时含有大小写字母、数字、特殊字符中的两种'))
        } else {
          let str = validateContinue(value)
          if (str) {
            callback(new Error(`存在连续字符${str}`))
          } else {
            callback()
          }
        }
      }  
    }
  }
}
</script>

<style lang="less" scoped>
.my-account-container{
  width: 100%;
  height: 100%;
  background: rgba(248,249,253,1);
  padding: 30px 20px 0 20px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-size: 14px;
  .box-card{
    width: 100%;
    padding: 20px 20px 28px 20px;
    background-color: #fff;
    .title{
      font-size: 18px;
      font-weight: 500;
      color: #333333;
    }
    .info-wrap{
      margin-top: 20px;
      .info-item{
        display: flex;
        margin-bottom: 20px;
        font-weight: 400;
        align-items: center;
        .name{
          width: 70px;
          color: #222222;
          margin-right: 13px;
        }
        .content{
          display: flex;
          align-items: center;
          .content-info{
            color: #666666;
            margin-right: 15px;
          }
          .content-icon{            
            font-size: 12px;
            color: #4B7EFE;
            text-decoration: underline;
            cursor: pointer;
            margin-right: 5px;
          }
          .bind-icon{
            margin-left: -15px;
          }
        }
      }
    }
  }
  .passRule{
    width: 562px;
    height: 116px;
    background: #F2F4F8;
    padding: 10px 47px 10px 20px;
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    .title{
      width: 464px;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #4B7EFE;
      line-height: 24px;
    }
    .word{
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #666666;
      line-height: 24px;
    }
  }
}
.search-btn{
  background-color: #4B7EFE;
  border: none;
}
</style>